package com.yoki.cloud.common.protocol.radius.attribute.attr;

import com.yoki.cloud.common.protocol.radius.exception.RadiusException;
import lombok.Getter;
import lombok.ToString;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2017/10/24$ 20:44$
 */
@ToString(callSuper = true)
public abstract class RadiusMsgAttr<T> extends RawRadiusMsgAttr {

    /**
     * (length - 2) bytes
     */
    @Getter
    protected T value;

    /**
     * 通过字节数组解析成value值<br></br>
     * <span color=red><b>子类进行复写此方法</b></span>
     *
     * @return
     */
    protected abstract T parseValue(byte[] input);

    public void parse(int type, byte[] attrValue){
        parseRaw(type, attrValue);
        value = parseValue(valueRawBytes);
    }

    public void parse(byte[] bytes) throws RadiusException {
        parseRaw(bytes);
        value = parseValue(valueRawBytes);
    }

    public byte[] getBytes() {
        byte[] valueBytes = getValueBytes();
        if (null == valueBytes) {
            return new byte[0];
        }
        byte[] bytes = new byte[LENGTH_TYPE + LENGTH_LENGTH + valueBytes.length];
        length = bytes.length;
        bytes[0] = (byte) (getAttrType() & 0xff);
        bytes[1] = (byte) (length & 0xff);

        System.arraycopy(valueBytes, 0, bytes, (LENGTH_TYPE + LENGTH_LENGTH), valueBytes.length);
        return bytes;
    }

    /**
     * 获取value的字节数组<br></br>
     * <span color=red><b>子类进行复写此方法</b></span>
     *
     * @return
     */
    protected abstract byte[] getValueBytes();

    @Override
    protected void rest() {
        this.type = -1;
        this.length = -1;
        this.valueRawBytes = null;
        this.value = null;
    }

    /*@Override
    public String toString() {
        return super.toString();
    }*/
}
